<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input placeholder="Title" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-if="checkPermission(rolePageRole.rolePage_retrieve)" v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        Search
      </el-button>
      <el-button v-if="checkPermission(rolePageRole.rolePage_create)" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="角色id" sortable="custom" align="center" width="60" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.roleId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" sortable="custom" align="center" width="200">
        <template slot-scope="{row}">
          <span>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" sortable="custom" align="center" width="200">
        <template slot-scope="{row}">
          <span>{{ row.roleDesc }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" align="center" width="400">
        <template slot-scope="{row}">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" sortable="custom" align="center" width="400">
        <template slot-scope="{row}">
          <el-popover
            placement="right"
            width="400"
            trigger="click"
          >
            <el-descriptions title="用户信息">
              <el-descriptions-item label="角色名称">{{ row.roleName }} </el-descriptions-item>
              <el-descriptions-item label="描述">{{ row.roleDesc }}</el-descriptions-item>
            </el-descriptions>
            <el-button slot="reference" @click="hanleRoleDetail(row.roleId)">详情</el-button>
          </el-popover>
          <el-button v-if="checkPermission(rolePageRole.rolePage_update)" @click="handleModify(row)">修改</el-button>
          <el-button v-if="checkPermission(rolePageRole.rolePage_delete)" @click="handleDeleteRole(row.$index, row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!--  add  -->
    <el-dialog title="添加角色" :visible.sync="createDialogVisible">
      <el-form ref="dataForm" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="角色名称">
          <el-input v-model="addRole.roleName" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="addRole.roleDesc"
            type="textarea"
            :rows="2"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">
          Cancel
        </el-button>
        <el-button @click="handleCreateCommit">
          Ok
        </el-button>
      </div>
    </el-dialog>
    <!--  删除角色  -->
    <el-dialog title="删除角色" :visible.sync="deleteDialogVisible">
      <div>
        角色:
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">
          Cancel
        </el-button>
        <el-button @click="deleteRow(deleteIndex, list);deleteDialogVisible=false;">
          Ok
        </el-button>
      </div>
    </el-dialog>
    <!--  修改角色  -->
    <el-dialog title="修改角色授权资源" :visible.sync="modifyDialogVisible">
      <div>
        <el-col :span="6">
          <el-tag>角色授权资源</el-tag>
          <el-tree
            ref="tree"
            :data="focusedRoleData.pages"
            show-checkbox
            default-expand-all
            node-key="id"
            highlight-current
          />
        </el-col>
        <el-col :span="6">
          <el-tag>授权用户列表</el-tag>
          <div>
            <el-tree
              ref="tree"
              :data="focusedRoleData.users"
              show-checkbox
              default-expand-all
              node-key="id"
              highlight-current
              :props="focusedRoleData.userProps"
            />
          </div>
        </el-col><br><br><br><br><br><br>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">
          Cancel
        </el-button>
        <el-button @click="deleteRow(deleteIndex, list);deleteDialogVisible=false;">
          Ok
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import permission from '@/directive/permission' // 权限判断指令
import checkPermission from '@/utils/permission'
import '@/utils/validate'
import waves from '@/directive/waves'
import { fetchAllRoles } from '@/api/rolePage/rolePageApi'
import {
  getAllResourceAndAllOptions,
  getAllUserByRoleId,
  getPermissionIdsByRoleId
} from '@/api/authorize/authorizePageApi'
import { addRole, deleteRole, fetchPageRolesByPageName } from '@/api/role'

export default {
  components: { Pagination },
  directives: { waves, permission },
  data() {
    return {
      rolePageRole: {
        rolePage_retrieve: ['admin'],
        rolePage_update: ['admin'],
        rolePage_delete: ['admin'],
        rolePage_create: ['admin']
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      createDialogVisible: false,
      addRole: { name: '' },
      deleteDialogVisible: false,
      deleteRole: { id: -1, role: '', resources: [] },
      deleteIndex: -1,
      modifyDialogVisible: false,
      resources: {
        pages: [],
        activeName: 'userManage',
        checkedIds: []
      },
      users: [{ id: 1, name: '超级管理员' }],
      focusedRoleData: {
        roleId: 0,
        pages: [{
          label: '用户管理',
          name: 'userManager',
          id: 1,
          children: [{ label: '添加用户', id: 3 }, { label: '删除用户', id: 4 }] },
        {
          label: '角色管理',
          name: 'roleManager',
          id: 2,
          children: [{ label: '添加角色', id: 4 }, { label: '删除角色', id: 5 }]
        }],
        users: [{ id: 1, name: '超级管理员' }],
        userProps: {
          label: 'name'
        }
      }
    }
  },
  async created() {
    await this.getList()
    // rolePageRole
    await fetchPageRolesByPageName('rolePage').then(response => {
      this.rolePageRole = response.data
      console.log('-----------------')
      console.log(this.rolePageRole)
      console.log(response.data)
      console.log('-----------------')
    })
  },
  methods: {
    checkPermission,
    hanleRoleDetail(id) {
      getAllResourceAndAllOptions().then(response => {
        this.resources.pages = response.data
        console.log(this.resources)
      })
      getAllUserByRoleId({ 'roleId': id }).then(response => {
        this.users = []
        const data = response.data.items
        for (const i in data) {
          this.users.push(data[i])
        }
        console.log(this.users)
      })
      getPermissionIdsByRoleId({ 'roleId': id }).then(response => {
        this.resources.checkedIds = []
        this.$refs.ResourceTree.setCheckedKeys([])
        for (const i in response.data) {
          this.resources.checkedIds.push(response.data[i])
        }
        console.log(this.resources.checkedIds)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleFilter() {
    },
    handleCreate() {
      this.createDialogVisible = true
    },
    getList() {
      this.listLoading = true
      console.log('getList')
      fetchAllRoles(this.listQuery).then(response => {
        console.log(response.data)
        this.list = response.data
        this.total = response.data.length

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleCreateCommit() {
      addRole(this.addRole).then(response => {
        this.addRole.roleName = ''
        this.addRole.roleDesc = ''
        this.createDialogVisible = false
        this.getList()
      }).then(response => {
        const h = this.$createElement
        this.$notify({
          title: '添加角色',
          message: h('i', { style: 'color: teal' }, '成功添加角色')
        })
      })
    },
    handleShowDetail() {

    },
    handleModify(row) {
      this.modifyDialogVisible = true
      this.focusedRoleData.roleId = row.id
    },
    deleteRow(index, rows) {
      if (this.deleteRole.roleId in [1, 2, 3]) {
        const h = this.$createElement
        this.$notify({
          title: '删除角色',
          message: h('i', { style: 'color: teal' }, '操作失败，受保护角色')
        })
        return
      }
      deleteRole({ 'roleId': this.deleteRole.roleId }).then(response => {
        this.getList()
        const h = this.$createElement
        this.$notify({
          title: '删除角色',
          message: h('i', { style: 'color: teal' }, '操作成功')
        })
      })
    },
    handleDeleteRole(index, row) {
      alert('delete')
      this.deleteIndex = index
      this.deleteDialogVisible = true
      this.deleteRole = row
    },
    countLength(arr) {
      return arr.length
    }
  }
}
</script>

<style scoped>

</style>
